import { Fragment, useRef, useEffect, useState, useCallback } from 'react';
import * as echarts from 'echarts/core';
import { TooltipComponent, LegendComponent } from 'echarts/components';
import { PieChart } from 'echarts/charts';
import { LabelLayout } from 'echarts/features';
import { SVGRenderer } from 'echarts/renderers';
import { http } from '@/utils/http';

export const HomePieChart = () => {
  const { username } = JSON.parse(window.sessionStorage.getItem('news'))

  const [newsList, setNewsList] = useState([])  // 已发布的新闻列表

  // 获取新闻列表
  const getNewsList = useCallback(async () => {
    const { data } = await http.get(`/news?publishState=2&author=${username}&_expand=category`)
    // console.log(data)
    // 处理数据
    const formatData = data.map(item => item.category.title)
    // console.log(formatData)
    let sum = {};
    for (let i = 0; i < formatData.length; i++) {
      if (sum[formatData[i]]) {
        sum[formatData[i]] += 1
      } else {
        sum[formatData[i]] = 1
      }
    }

    let list = [];
    for (let j in sum) {
      list.push({
        name: j,
        value: sum[j]
      })
    }
    setNewsList(list)

  }, [username])

  useEffect(() => {
    getNewsList()
  }, [getNewsList])

  // 绑定ref供echart初始化实例使用
  const domRef = useRef(null);

  useEffect(() => {

    echarts.use([
      TooltipComponent,
      LegendComponent,
      PieChart,
      SVGRenderer,
      LabelLayout
    ]);
    // echart初始化
    var myChart = echarts.getInstanceByDom(domRef.current); //有的话就获取已有echarts实例的DOM节点。
    if (myChart == null) { // 如果不存在，就进行初始化。
      myChart = echarts.init(domRef.current, null, {
        renderer: 'svg'
      });
    }

    var option;

    option = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        top: '5%%',
        left: 'center'
      },
      series: [
        {
          name: '发布数量',
          type: 'pie',
          radius: ['40%', '75%'],
          avoidLabelOverlap: true,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '35',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: newsList
        }
      ]
    };

    option && myChart.setOption(option);
  }, [newsList])
  return (
    <Fragment>
      <div ref={domRef} style={{ width: '400px', height: '100%', marginLeft: '-20px' }} />
    </Fragment>
  )
}